<template>
  <div class="city-comparison-page">
    <a-row :gutter="16">
      <a-col :span="24">
        <a-card title="城市房价对比" :bordered="false">
          <a-form layout="inline">
            <a-form-item label="选择城市">
              <a-select
                v-model:value="selectedCities"
                mode="multiple"
                style="width: 400px"
                placeholder="选择要对比的城市"
                :options="cityOptions"
                @change="handleCitiesChange"
              ></a-select>
            </a-form-item>
            
            <a-form-item>
              <a-button type="primary" @click="fetchComparisonData" :loading="loading">
                对比分析
              </a-button>
            </a-form-item>
          </a-form>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCities.length > 0">
      <a-col :span="24">
        <a-card :bordered="false" title="城市房价统计对比">
          <a-table
            :dataSource="statisticsData"
            :columns="statisticsColumns"
            :pagination="false"
            :loading="loading"
            rowKey="city"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'avgPrice' || column.dataIndex === 'medianPrice'">
                <span :style="{ color: '#f5222d', fontWeight: 'bold' }">{{ record[column.dataIndex] }} 万元</span>
              </template>
              
              <template v-if="column.dataIndex === 'avgUnitPrice'">
                <span :style="{ color: '#f5222d', fontWeight: 'bold' }">{{ record[column.dataIndex] }} 万元/㎡</span>
              </template>
              
              <template v-if="column.dataIndex === 'avgArea'">
                <span>{{ record[column.dataIndex] }} ㎡</span>
              </template>
            </template>
          </a-table>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCities.length > 0">
      <a-col :span="12">
        <a-card :bordered="false" title="均价对比">
          <div ref="avgPriceChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
      
      <a-col :span="12">
        <a-card :bordered="false" title="单价对比">
          <div ref="unitPriceChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCities.length > 0">
      <a-col :span="24">
        <a-card :bordered="false" title="价格区间分布对比">
          <div ref="priceDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
    
    <a-row :gutter="16" style="margin-top: 16px" v-if="selectedCities.length > 0">
      <a-col :span="24">
        <a-card :bordered="false" title="面积区间分布对比">
          <div ref="areaDistChartRef" style="width: 100%; height: 400px"></div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch, nextTick } from 'vue'
import { useHouseStore } from '../stores/houseStore'
import { useAnalysisStore } from '../stores/analysisStore'
import { message } from 'ant-design-vue'
import * as echarts from 'echarts'

// 初始化 store
const houseStore = useHouseStore()
const analysisStore = useAnalysisStore()

// 状态
const loading = ref(false)
const selectedCities = ref([])
const cityOptions = ref([])
const statisticsData = ref([])

// 图表引用
const avgPriceChartRef = ref(null)
const unitPriceChartRef = ref(null)
const priceDistChartRef = ref(null)
const areaDistChartRef = ref(null)

// 图表实例
let avgPriceChart = null
let unitPriceChart = null
let priceDistChart = null
let areaDistChart = null

// 表格列定义
const statisticsColumns = [
  {
    title: '城市',
    dataIndex: 'city',
    key: 'city',
    width: 100
  },
  {
    title: '房源数量',
    dataIndex: 'houseCount',
    key: 'houseCount',
    width: 120,
    sorter: (a, b) => a.houseCount - b.houseCount
  },
  {
    title: '平均总价(万元)',
    dataIndex: 'avgPrice',
    key: 'avgPrice',
    width: 150,
    sorter: (a, b) => a.avgPrice - b.avgPrice
  },
  {
    title: '中位数总价(万元)',
    dataIndex: 'medianPrice',
    key: 'medianPrice',
    width: 150,
    sorter: (a, b) => a.medianPrice - b.medianPrice
  },
  {
    title: '平均单价(万元/㎡)',
    dataIndex: 'avgUnitPrice',
    key: 'avgUnitPrice',
    width: 150,
    sorter: (a, b) => a.avgUnitPrice - b.avgUnitPrice
  },
  {
    title: '平均面积(㎡)',
    dataIndex: 'avgArea',
    key: 'avgArea',
    width: 120,
    sorter: (a, b) => a.avgArea - b.avgArea
  }
]

// 处理城市选择变化
const handleCitiesChange = (values) => {
  selectedCities.value = values
}

// 获取对比数据
const fetchComparisonData = async () => {
  if (selectedCities.value.length === 0) {
    message.warning('请至少选择一个城市进行对比')
    return
  }
  
  loading.value = true
  
  try {
    // 清空之前的数据
    statisticsData.value = []
    
    // 获取每个城市的统计数据
    for (const city of selectedCities.value) {
      const stats = await analysisStore.fetchCityStatistics(city)
      const priceDistribution = await analysisStore.fetchPriceDistribution(city)
      const areaDistribution = await analysisStore.fetchAreaDistribution(city)
      
      // 调试日志
      console.log(`城市 [${city}] 价格分布数据:`, priceDistribution)
      console.log(`城市 [${city}] 面积分布数据:`, areaDistribution)
      
      statisticsData.value.push({
        city: city,
        houseCount: stats.houseCount || 0,
        avgPrice: stats.avgPrice?.toFixed(2) || 0,
        medianPrice: stats.medianPrice?.toFixed(2) || 0,
        avgUnitPrice: stats.avgUnitPrice?.toFixed(2) || 0,
        avgArea: stats.avgArea?.toFixed(1) || 0,
        priceDistribution: priceDistribution,
        areaDistribution: areaDistribution
      })
    }
    
    console.log('所有统计数据:', statisticsData.value)
    
    // 更新图表
    nextTick(() => {
      initAvgPriceChart()
      initUnitPriceChart()
      initPriceDistChart()
      initAreaDistChart()
    })
  } catch (error) {
    console.error('获取城市对比数据失败:', error)
    message.error('获取城市对比数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化均价对比图表
const initAvgPriceChart = () => {
  if (!avgPriceChartRef.value) return
  
  avgPriceChart = echarts.init(avgPriceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['平均总价', '中位数总价']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: statisticsData.value.map(item => item.city)
    },
    yAxis: {
      type: 'value',
      name: '价格(万元)'
    },
    series: [
      {
        name: '平均总价',
        type: 'bar',
        data: statisticsData.value.map(item => parseFloat(item.avgPrice)),
        itemStyle: {
          color: '#1890ff'
        }
      },
      {
        name: '中位数总价',
        type: 'bar',
        data: statisticsData.value.map(item => parseFloat(item.medianPrice)),
        itemStyle: {
          color: '#13c2c2'
        }
      }
    ]
  }
  
  avgPriceChart.setOption(option)
}

// 初始化单价对比图表
const initUnitPriceChart = () => {
  if (!unitPriceChartRef.value) return
  
  unitPriceChart = echarts.init(unitPriceChartRef.value)
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: statisticsData.value.map(item => item.city)
    },
    yAxis: {
      type: 'value',
      name: '单价(万元/㎡)'
    },
    series: [
      {
        type: 'bar',
        data: statisticsData.value.map(item => parseFloat(item.avgUnitPrice)),
        itemStyle: {
          color: '#fa8c16'
        },
        label: {
          show: true,
          position: 'top',
          formatter: '{c} 万元/㎡'
        }
      }
    ]
  }
  
  unitPriceChart.setOption(option)
}

// 初始化价格分布对比图表
const initPriceDistChart = () => {
  if (!priceDistChartRef.value) return
  
  priceDistChart = echarts.init(priceDistChartRef.value)
  
  // 获取所有城市的价格区间，合并去重
  let allRanges = new Set()
  
  for (const cityData of statisticsData.value) {
    // 检查不同可能的数据结构
    if (cityData.priceDistribution?.priceDistribution) {
      // 如果是嵌套的priceDistribution结构
      Object.keys(cityData.priceDistribution.priceDistribution).forEach(range => allRanges.add(range))
    } else if (cityData.priceDistribution?.ranges) {
      // 如果是ranges数组结构
      cityData.priceDistribution.ranges.forEach(range => allRanges.add(range))
    } else if (typeof cityData.priceDistribution === 'object' && !Array.isArray(cityData.priceDistribution)) {
      // 如果是普通对象结构
      Object.keys(cityData.priceDistribution).forEach(key => {
        if (key !== 'city' && key !== 'ranges' && key !== 'counts' && key !== 'data') {
          allRanges.add(key)
        }
      })
    }
  }
  
  // 将集合转换为数组并排序
  const priceRanges = Array.from(allRanges).sort((a, b) => {
    // 提取价格区间的起始值用于排序
    const aMatch = a.match(/^(\d+)/)
    const bMatch = b.match(/^(\d+)/)
    const aVal = aMatch ? parseInt(aMatch[1]) : 0
    const bVal = bMatch ? parseInt(bMatch[1]) : 0
    return aVal - bVal
  })
  
  console.log('价格区间：', priceRanges)
  
  // 处理每个城市的系列数据
  const series = selectedCities.value.map(city => {
    const cityData = statisticsData.value.find(item => item.city === city)
    let cityPriceData = []
    
    if (cityData) {
      // 根据不同的数据结构获取数据
      if (cityData.priceDistribution?.priceDistribution) {
        cityPriceData = priceRanges.map(range => cityData.priceDistribution.priceDistribution[range] || 0)
      } else if (cityData.priceDistribution?.ranges && cityData.priceDistribution?.counts) {
        // 如果数据是以ranges和counts数组形式提供的
        cityPriceData = priceRanges.map(range => {
          const index = cityData.priceDistribution.ranges.indexOf(range)
          return index !== -1 ? cityData.priceDistribution.counts[index] : 0
        })
      } else {
        // 直接从对象中获取
        cityPriceData = priceRanges.map(range => {
          // 排除非数据字段
          if (typeof cityData.priceDistribution[range] === 'number') {
            return cityData.priceDistribution[range]
          }
          return 0
        })
      }
    }
    
    return {
      name: city,
      type: 'bar',
      data: cityPriceData,
      emphasis: {
        focus: 'series',
        label: {
          show: true,
          formatter: '{c}套',
          position: 'top'
        }
      }
    }
  })
  
  const option = {
    title: {
      text: '各城市不同价格区间房源数量分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = `${params[0].axisValueLabel}<br/>`
        params.forEach(param => {
          result += `${param.marker} ${param.seriesName}: ${param.value}套<br/>`
        })
        return result
      }
    },
    legend: {
      data: selectedCities.value,
      top: 30
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: priceRanges,
      name: '价格区间',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '房源数量(套)'
    },
    series: series,
    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452']
  }
  
  priceDistChart.setOption(option)
}

// 初始化面积分布对比图表
const initAreaDistChart = () => {
  if (!areaDistChartRef.value) return
  
  areaDistChart = echarts.init(areaDistChartRef.value)
  
  // 获取所有城市的面积区间，合并去重
  let allRanges = new Set()
  
  for (const cityData of statisticsData.value) {
    // 检查不同可能的数据结构
    if (cityData.areaDistribution?.areaDistribution) {
      // 如果是嵌套的areaDistribution结构
      Object.keys(cityData.areaDistribution.areaDistribution).forEach(range => allRanges.add(range))
    } else if (cityData.areaDistribution?.ranges) {
      // 如果是ranges数组结构
      cityData.areaDistribution.ranges.forEach(range => allRanges.add(range))
    } else if (cityData.areaDistribution?.labels) {
      // 如果是labels数组结构
      cityData.areaDistribution.labels.forEach(label => allRanges.add(label))
    } else if (typeof cityData.areaDistribution === 'object' && !Array.isArray(cityData.areaDistribution)) {
      // 如果是普通对象结构
      Object.keys(cityData.areaDistribution).forEach(key => {
        if (key !== 'city' && key !== 'ranges' && key !== 'labels' && key !== 'counts' && key !== 'data') {
          allRanges.add(key)
        }
      })
    }
  }
  
  // 将集合转换为数组并排序
  const areaRanges = Array.from(allRanges).sort((a, b) => {
    // 提取面积区间的起始值用于排序
    const aMatch = a.match(/^(\d+)/)
    const bMatch = b.match(/^(\d+)/)
    const aVal = aMatch ? parseInt(aMatch[1]) : 0
    const bVal = bMatch ? parseInt(bMatch[1]) : 0
    return aVal - bVal
  })
  
  console.log('面积区间：', areaRanges)
  
  // 处理每个城市的系列数据
  const series = selectedCities.value.map(city => {
    const cityData = statisticsData.value.find(item => item.city === city)
    let cityAreaData = []
    
    if (cityData) {
      // 根据不同的数据结构获取数据
      if (cityData.areaDistribution?.areaDistribution) {
        cityAreaData = areaRanges.map(range => cityData.areaDistribution.areaDistribution[range] || 0)
      } else if (cityData.areaDistribution?.ranges && cityData.areaDistribution?.counts) {
        // 如果数据是以ranges和counts数组形式提供的
        cityAreaData = areaRanges.map(range => {
          const index = cityData.areaDistribution.ranges.indexOf(range)
          return index !== -1 ? cityData.areaDistribution.counts[index] : 0
        })
      } else if (cityData.areaDistribution?.labels && cityData.areaDistribution?.counts) {
        // 如果数据是以labels和counts数组形式提供的
        cityAreaData = areaRanges.map(range => {
          const index = cityData.areaDistribution.labels.indexOf(range)
          return index !== -1 ? cityData.areaDistribution.counts[index] : 0
        })
      } else {
        // 直接从对象中获取
        cityAreaData = areaRanges.map(range => {
          // 排除非数据字段
          if (typeof cityData.areaDistribution[range] === 'number') {
            return cityData.areaDistribution[range]
          }
          return 0
        })
      }
    }
    
    return {
      name: city,
      type: 'bar',
      data: cityAreaData,
      emphasis: {
        focus: 'series',
        label: {
          show: true,
          formatter: '{c}套',
          position: 'top'
        }
      }
    }
  })
  
  const option = {
    title: {
      text: '各城市不同面积区间房源数量分布',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      },
      formatter: function(params) {
        let result = `${params[0].axisValueLabel}<br/>`
        params.forEach(param => {
          result += `${param.marker} ${param.seriesName}: ${param.value}套<br/>`
        })
        return result
      }
    },
    legend: {
      data: selectedCities.value,
      top: 30
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: areaRanges,
      name: '面积区间',
      nameLocation: 'middle',
      nameGap: 30,
      axisLabel: {
        rotate: 45,
        interval: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '房源数量(套)'
    },
    series: series,
    color: ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#73c0de', '#3ba272', '#fc8452']
  }
  
  areaDistChart.setOption(option)
}

// 监听窗口大小变化，重绘图表
window.addEventListener('resize', () => {
  avgPriceChart?.resize()
  unitPriceChart?.resize()
  priceDistChart?.resize()
  areaDistChart?.resize()
})

// 页面加载时获取数据
onMounted(async () => {
  try {
    // 获取城市列表
    const cities = await houseStore.fetchCities()
    cityOptions.value = cities.map(city => ({
      label: city,
      value: city
    }))
    
    // 默认选择前两个城市
    if (cities.length >= 2) {
      selectedCities.value = [cities[0], cities[1]]
      await fetchComparisonData()
    } else if (cities.length === 1) {
      selectedCities.value = [cities[0]]
      await fetchComparisonData()
    }
  } catch (error) {
    console.error('获取城市列表失败:', error)
    message.error('获取城市列表失败')
  }
})
</script>

<style scoped lang="scss">
.city-comparison-page {
  padding: 24px;
}
</style> 